package btctx

import (
	"bytes"
	"encoding/hex"

	"github.com/btcsuite/btcd/wire"
	"github.com/btcsuite/btcutil"
)

func EncodeTxBytes(tx *wire.MsgTx) ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	err := tx.Serialize(buf)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func EncodeTxString(tx *wire.MsgTx) (string, error) {
	raw, err := EncodeTxBytes(tx)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(raw), nil
}

func DecodeTxString(rawtx string) (*wire.MsgTx, error) {
	raw, err := hex.DecodeString(rawtx)
	if err != nil {
		return nil, err
	}
	tx, err := btcutil.NewTxFromBytes(raw)
	if err != nil {
		return nil, err
	}
	return tx.MsgTx(), nil
}
